﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Transactions;
using BCL.Entity;
using NazSoft.Framework;
using System.Linq;
using NazSoft.Framework.Extensions;

namespace BCL.Repository
{
    public class NewsRepository
    {
        public int Activate(int logoInformationId)
        {
            SqlHelper helpclass = new SqlHelper();

            var activated = helpclass.ExecuteNonQuery("ActivateLogoInformation", new object[] { "Id" }, new object[] { logoInformationId });


            #region clear from cache
            try
            {
                var logoInformation = Get(logoInformationId);
                String cacheKey = "GetNews" + logoInformation.CurrentDate.Date.ToString();
                CacheHelper.Clear(cacheKey);
                CacheHelper.Clear("GetNews");
            }
            catch (Exception ex) { };
            #endregion


            return activated;
        }

        public int Inactivate(int logoInformationId)
        {
            SqlHelper helpclass = new SqlHelper();

            var activated = helpclass.ExecuteNonQuery("InactivateLogoInformation", new object[] { "Id" }, new object[] { logoInformationId });



            #region clear from cache
            try
            {
                var logoInformation = Get(logoInformationId);
                String cacheKey = "GetNews" + logoInformation.CurrentDate.Date.ToString();
                CacheHelper.Clear(cacheKey);
                CacheHelper.Clear("GetNews");
            }
            catch (Exception ex) { };
            #endregion



            return activated;
        }

        public Commercial GetCommercial(string name)
        {
            object[] objName = { "Name" };
            object[] objValue = { name };

            SqlHelper helpclass = new SqlHelper();
            DataTable dataTable = helpclass.GetDataTable("SpGetCommercialByName", objName, objValue);
            if (dataTable.Rows.Count != 0)
            {
                Commercial model = CollectionHelper.CreateItem<Commercial>(dataTable.Rows[0]);

                return model;
            }
            return null;
        }
        #region SaveMethod
        public int Save(LogoInformation logoInformation)
        {
            using (TransactionScope t = new TransactionScope(TransactionScopeOption.Suppress))
            {

                int id = 0;
                if (logoInformation.Id != 0)
                {

                    logoInformation.UpdatedDate = DatetimeUtility.GetCurrentDateTime();
                    id = this.Update(logoInformation);
                }
                else
                {
                    logoInformation.CreatedDate = DatetimeUtility.GetCurrentDateTime();
                    id = this.SaveLogoInformation(logoInformation);
                }

                t.Complete();
                CacheHelper.ClearAll();
                return id;
            }


        }
        private int SaveLogoInformation(LogoInformation logoInformation)
        {
            object[] objName = { "CurrentDate", "FarmanImage", "HeaderImage", "LogoImage", "CreatedBy", "CreatedDate" };
            object[] objValue = { logoInformation.CurrentDate,logoInformation.FarmanImage, logoInformation.HeaderImage,logoInformation.LogoImage,
                                logoInformation.CreatedBy, logoInformation.CreatedDate};

            var parameter = new System.Data.SqlClient.SqlParameter("@Id", 0);
            //cmd.Parameters.Add("@Id", SqlDbType.Int, 0, "CategoryID");
            parameter.Direction = ParameterDirection.Output;

            SqlHelper helpclass = new SqlHelper();
            var result = helpclass.ExecuteNonQuery("SP_LogInformationInsert", objName, objValue, (cmd) =>
            {
                cmd.Parameters.Add(parameter);
            });
            int Id = Convert.ToString(parameter.Value).ToInt32Safe();

            if (Id != -1)
                if (logoInformation.Detail != null)
                {
                    foreach (var item in logoInformation.Detail)
                    {
                        item.LogoInformationId = Id;
                        int detailId = SaveDetail(item);
                        if (item.DetailToDetail != null)
                        {
                            foreach (var detailToDetail in item.DetailToDetail)
                            {
                                detailToDetail.LogoDetailId = detailId;
                                if (detailToDetail.Scripts == null)
                                    detailToDetail.Scripts = "<img src='" + detailToDetail.FileName + "' alt=''>";
                                SaveDetailToDetail(detailToDetail);
                            }
                        }
                    }
                }

            return Id;
        }

        private int SaveDetail(LogoDetail logoDetail)
        {
            object[] objName = { "MenuId", "LogoInformationId", "NoOfFilePerPage", "Tags" };
            object[] objValue = { logoDetail.MenuId, logoDetail.LogoInformationId, logoDetail.NoOfFilePerPage, logoDetail.Tags };
            var parameter = new System.Data.SqlClient.SqlParameter("@Id", 0);
            //cmd.Parameters.Add("@Id", SqlDbType.Int, 0, "CategoryID");
            parameter.Direction = ParameterDirection.Output;

            SqlHelper helpclass = new SqlHelper();
            var result = helpclass.ExecuteNonQuery("SP_LogDetailInsert", objName, objValue, (cmd) =>
            {
                cmd.Parameters.Add(parameter);
            });
            int Id = Convert.ToString(parameter.Value).ToInt32Safe();//helpclass.ExecuteNonQuery("SP_LogDetailInsert", objName, objValue);
            return Id;
        }

        private int SaveDetailToDetail(LogoDetailDetail logoDetailDetail)
        {
            object[] objName = { "LogoDetailId", "OrderNo", "FileName", "Description", "Script", "MenuId" };
            object[] objValue = { logoDetailDetail.LogoDetailId, logoDetailDetail.OrderNo, logoDetailDetail.FileName, logoDetailDetail.Description, logoDetailDetail.Scripts, logoDetailDetail.MenuId };

            SqlHelper helpclass = new SqlHelper();
            int Id = helpclass.ExecuteNonQuery("SP_LogoDetailDetailInsert", objName, objValue);
            return Id;
        }
        #endregion

        #region Update
        public int Update(LogoInformation logoInformation)
        {
            object[] objName = { "CurrentDate", "FarmanImage", "HeaderImage", "LogoImage", "UpdatedBy", "UpdatedDate", "Id" };
            object[] objValue = { logoInformation.CurrentDate,logoInformation.FarmanImage, logoInformation.HeaderImage,logoInformation.LogoImage,
                                logoInformation.UpdatedBy, logoInformation.UpdatedDate, logoInformation.Id};

            SqlHelper helpclass = new SqlHelper();
            int Id = helpclass.ExecuteNonQuery("SP_LogoInformationUpdate", objName, objValue);

            if (Id != -1)
                if (logoInformation.Detail != null)
                {
                    foreach (var item in logoInformation.Detail)
                    {
                        //item.LogoInformationId = Id; 
                        item.LogoInformationId = logoInformation.Id;
                        int detailId = SaveDetail(item);
                        if (item.DetailToDetail != null)
                        {
                            foreach (var detailToDetail in item.DetailToDetail)
                            {
                                detailToDetail.LogoDetailId = detailId;
                                SaveDetailToDetail(detailToDetail);
                            }
                        }
                    }
                }

            return Id;
        }


        #endregion

        #region Get Record
        public LogoInformation Get(int Id)
        {

            object[] objName = { "Id" };
            object[] objValue = { Id };

            SqlHelper helpclass = new SqlHelper();
            DataSet dataSet = helpclass.GetDataSet("SP_LogoInformationById", objName, objValue);

            LogoInformation model = ConvertDataSetToLogoInformation(dataSet);

            return model;
        }

        private LogoInformation ConvertDataSetToLogoInformation(DataSet dataSet)
        {
            // properties name of UserInfo object must match the column names returned by SP
            LogoInformation model = null;

            if (dataSet.Tables != null && dataSet.Tables.Count > 0)
            {
                model = CollectionHelper.ConvertTo<LogoInformation>(dataSet.Tables[0]).FirstOrDefault();
                if (model != null)
                {
                    model.Detail = CollectionHelper.ConvertTo<LogoDetail>(dataSet.Tables[1]).ToList();
                    var v = CollectionHelper.ConvertTo<LogoDetailDetail>(dataSet.Tables[2]).ToList();

                    foreach (var item in model.Detail)
                    {
                        item.DetailToDetail = v.Where(t => t.LogoDetailId == item.Id).ToList();
                    }

                }
            }

            return model;
        }

        public LogoInformation Get(DateTime? currentDate, bool isPreview)
        {
            String cacheKey = "GetNews";
            if (currentDate.HasValue)
            {
                cacheKey = "GetNews" + currentDate.Value.Date.ToString();
            }

            var data = CacheHelper.Get<LogoInformation>(cacheKey);

            if (data == null)
            {
                data = GetFromDatabase(currentDate, isPreview);

                if (data != null)
                {
                    CacheHelper.Add(data, cacheKey);
                }
            }

            return data;
        }

        public LogoInformation GetHeadlines(DateTime? currentDate, bool isPreview)
        {
            String cacheKey = "HeadLines";
            //if (currentDate.HasValue)
            //{
            //    cacheKey = "GetNews" + currentDate.Value.Date.ToString();
            //}

            var data = CacheHelper.Get<LogoInformation>(cacheKey);

            if (data == null)
            {
                data = GetFromDatabase(currentDate, isPreview);

                if (data != null)
                {
                    CacheHelper.Add(data, cacheKey);
                }
            }

            return data;
        }

        public LogoInformation GetFromDatabase(DateTime? currentDate, bool isPreview)
        {
            object[] objName = { "CurrentDate", "IsPreview" };
            object[] objValue = { currentDate.HasValue ? Convert.ToString(currentDate.Value.Date) : null, isPreview };

            SqlHelper helpclass = new SqlHelper();
            DataSet dataSet = helpclass.GetDataSet("SP_LogoInformation", objName, objValue);

            LogoInformation model = ConvertDataSetToLogoInformation(dataSet);

            return model;
        }

        public int InactivateCommercial(int id)
        {
            SqlHelper helpclass = new SqlHelper();

            var activated = helpclass.ExecuteNonQuery("InactivateCommercial", new object[] { "Id" }, new object[] { id });


            #region clear from cache
            String cacheKey = "GetCommercial";
            CacheHelper.Clear(cacheKey);
            #endregion


            return activated;
        }

        public int ActivateCommercial(int id)
        {
            SqlHelper helpclass = new SqlHelper();

            var activated = helpclass.ExecuteNonQuery("ActivateCommercial", new object[] { "Id" }, new object[] { id });


            #region clear from cache
            String cacheKey = "GetCommercial";
            CacheHelper.Clear(cacheKey);
            #endregion


            return activated;
        }

        public Commercial GetCommercial(int id)
        {
            object[] objName = { "Id" };
            object[] objValue = { id };

            SqlHelper helpclass = new SqlHelper();
            DataTable dataTable = helpclass.GetDataTable("GetCommercialById", objName, objValue);

            Commercial model = CollectionHelper.CreateItem<Commercial>(dataTable.Rows[0]);

            return model;
        }

        public List<Commercial> GetCommercial(DateTime currentDate)
        {
            String cacheKey = "GetCommercial";
            var data = CacheHelper.Get<List<Commercial>>(cacheKey);

            if (data == null)
            {
                data = GetCommercialFromDatabase(currentDate);

                if (data != null)
                {
                    CacheHelper.Add(data, cacheKey);
                }
            }

            return data;
        }

        public List<Commercial> GetCommercialFromDatabase(DateTime currentDate)
        {
            object[] objName = { "CurrentDate" };
            object[] objValue = { currentDate.Date };

            SqlHelper helpclass = new SqlHelper();
            DataTable dataTable = helpclass.GetDataTable("GetCommercial", objName, objValue);

            List<Commercial> model = CollectionHelper.ConvertTo<Commercial>(dataTable).ToList();

            return model;
        }

        public List<Commercial> GetCommercialFromDatabase1(DateTime currentDate)
        {
            object[] objName = { "CurrentDate" };
            object[] objValue = { currentDate.Date };

            SqlHelper helpclass = new SqlHelper();
            DataTable dataTable = helpclass.GetDataTable("GetCommercial12", objName, objValue);

            List<Commercial> model = CollectionHelper.ConvertTo<Commercial>(dataTable).ToList();

            return model;
        }

        public List<Commercial> SearchCommercials(String name, int typeId)
        {
            object[] objName = { "Name", "TypeId" };

            // set name to null here stored procedure needs null
            object[] objValue = { String.IsNullOrEmpty(name) ? null : name, typeId };

            SqlHelper helpclass = new SqlHelper();
            DataTable dataTable = helpclass.GetDataTable("SearchCommercials", objName, objValue);

            List<Commercial> model = CollectionHelper.ConvertTo<Commercial>(dataTable).ToList();

            return model;
        }

        public int SaveCommercials(List<Commercial> commercials)
        {
            String cacheKey = "GetCommercial";
            CacheHelper.Clear(cacheKey);

            SqlHelper helpclass = new SqlHelper();

            if (commercials != null && commercials.Count > 0)
            {
                var deleted = helpclass.ExecuteNonQuery("DeleteCommercial", new object[] { "TypeId" }, new object[] { commercials[0].TypeId });

                foreach (var commercial in commercials)
                {
                    object[] objName = { "Id", "Name", "Cost", "TypeId", "Script", "CreatedBy", "CreatedDate" };
                    object[] objValue = { commercial.CommercialId, commercial.Name, commercial.Cost, commercial.TypeId, commercial.Script, commercial.CreatedBy, commercial.CreatedDate.Date };


                    var result = helpclass.ExecuteNonQuery("SaveCommercial", objName, objValue);
                }

                return 1;
            }
            else
            {
                return -1;
            }
        }




        public List<LogoInformation> Search(DateTime? currentDate, int? menuId = null, int to = 0, int from = 1000)
        {
            object[] objName = { "CurrentDate", "To", "From", "MenuId" };
            object[] objValue = { currentDate, to, from, menuId };

            SqlHelper helpclass = new SqlHelper();
            DataSet dataSet = helpclass.GetDataSet("SearchLogoInformation", objName, objValue);

            List<LogoInformation> model = CollectionHelper.ConvertTo<LogoInformation>(dataSet.Tables[0]).ToList();

            return model;
        }

        public List<LogoInformation> ArchiveDate(DateTime? currentDate)
        {
            object[] objName = { };
            object[] objValue = { };

            SqlHelper helpclass = new SqlHelper();
            DataSet dataSet = helpclass.GetDataSet("ArchiveLogoDates", objName, objValue);

            List<LogoInformation> model = CollectionHelper.ConvertTo<LogoInformation>(dataSet.Tables[0]).ToList();

            return model;
        }

        #endregion

        //public bool Delete(int id)
        //{

        //}
    }
}
